<?php
namespace App\Handler;

use App\Exceptions\ResponseException;
use App\Http\Requests\Api\User\SendMsgRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

trait sendMsgHandler
{
    /**
     * 发送短信(待完善，目前缺乏短信接口)
     * User: ihome
     */
    public function sendSmsMsg($tel,$content)
    {
        //判断是否已经发送了数据
        $hashKey = 'send_msg:' . auth('api')->id() . ":" . $tel;

        //已经发送的时候返回
        if ($sendInfo = Redis::hgetall($hashKey)) {
            $returnData = [
                'send_status' => 1,
                'calcSecond'  => $sendInfo['send_time'] + 100 - time(),//100秒倒计时
                'verify_str'  => $sendInfo['rand_str'] //验证码的随机串
            ];

            throw new ResponseException(200, '已经发送过了', $returnData);
        }

        //未发送的时候
        $code    = mt_rand(100000, 999999);
        $content = '您的验证码为：' . $code;
        $to      = auth('api')->user()->email;

        \Mail::raw($content, function ($message) use ($to){
            $message->to($to)->subject('【验证码】-- Clannad商城');
        });

        //生成一个随机字符串
        $randStr = time() . mt_rand(22, 99) . '_rand_str';

        //将验证码存入到redis中
        $sendInfo = [
            'send_time' => time(),
            'rand_str'  => $randStr //验证码的随机串
        ];

        //存入redis
        Redis::hmset($hashKey, $sendInfo);
        Redis::expire($hashKey, 100); //60秒有效期

        Redis::setex($randStr, 300, $code);//设置这个key的有效期是300秒
        //返回

        throw new ResponseException(200, '发送成功', ['verify_str' => $randStr]);
    }

    /**
     * 检查验证码
     * User: ihome
     */
    public function checkCode(Request $request)
    {
        $code       = $request->input('sms_code');
        $tel        = $request->input('tel');
        $verify_str = $request->input('verify_str');

        $verify_code = Redis::get($verify_str);

        if ( ! $verify_code) {
            throw new ResponseException(400, '该验证码已过期，请重新发送');
        }

        if ($verify_code != $code) {
            throw new ResponseException(400, '验证码不正确');
        } else {
            $hashKey = 'send_msg:' . auth('api')->id() . ":" . $tel;
            Redis::del($verify_str);//确认完就清除掉
            Redis::del($hashKey);//确认完就清除掉

            //设置一个新的缓存，给修改密码的时候用的 时间是10分钟有效 10分钟后，不可再修改密码 需重新来过
            $rand_str = mt_rand(1111, 9999) . time() . '_rand_set_pswd';
            Redis::setex($rand_str, 600, auth('api')->id());//存入用户id 用于效验

            throw new ResponseException(200, 'ok', $rand_str);
        }
    }

    /**
     * 发送邮件
     * User: Clannad ~ ☆
     * Date: 2020/2/25 0025 12:01
     * @param $email string 邮箱
     * @param $title string 邮件标题
     * @param $content string 邮件内容
     * @throws ResponseException
     */
    public function sendEmailMsg($email,$title = "【新用户注册验证码】Clannad商城")
    {
        //判断是否已经发送了数据
        $hashKey = 'send_email:'. $email;

        //已经发送的时候返回
        if ($sendInfo = Redis::hgetall($hashKey)) {
            $returnData = [
                'send_status' => 1,
                'calcSecond'  => $sendInfo['send_time'] + 100 - time(),//100秒倒计时
                'verify_str'  => $sendInfo['rand_str'],//验证码的随机串
                'code' => Redis::get($sendInfo['rand_str']) //开发调试阶段 验证码直接返回给前端
            ];

            throw new ResponseException(200, '已经发送过了', $returnData);
        }

        //未发送的时候
        $code    = mt_rand(100000, 999999);
        $content = '您的验证码为：' . $code;

        \Mail::raw($content, function ($message) use ($email,$title){
            $message->to($email)->subject($title);
        });

        //生成一个随机字符串
        $randStr = time() . mt_rand(22, 99) . '_rand_str';

        //将验证码存入到redis中
        $sendInfo = [
            'send_time' => time(),
            'rand_str'  => $randStr //验证码的随机串
        ];

        //存入redis
        Redis::hmset($hashKey, $sendInfo);
        Redis::expire($hashKey, 100); //60秒有效期

        Redis::setex($randStr, 300, $code);//设置这个key的有效期是300秒
        //返回

        //开发调试阶段 验证码直接返回给前端
        throw new ResponseException(200, '发送成功', ['verify_str' => $randStr,'code'=>$code]);
    }


    /**
     * 检查微信验证码是否正确
     * User: Clannad ~ ☆
     * Date: 2020/2/25 0025 12:16
     * @throws ResponseException
     */
    public function checkEmailVerifyCode($email,$code,$verify_str)
    {
        $verify_code = Redis::get($verify_str);

        if ( ! $verify_code) {
            throw new ResponseException(400, '该验证码已过期，请重新发送');
        }

        if ($verify_code != $code) {
            throw new ResponseException(400, '验证码不正确');
        } else {
            $hashKey = 'send_email:' . $email;
            Redis::del($verify_str);//确认完就清除掉
            Redis::del($hashKey);//确认完就清除掉

            throw new ResponseException(200, 'ok');
        }
    }
}
